﻿using BaseData.CommonLib.Models;
using BaseData.CommonLib.Validators;
using BaseData.RazorLib.Services;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using Radzen;

namespace BaseData.RazorLib.Pages;

public partial class CustomerEdit
{
    private CustomerEditRequestDto _editRequestDto = new();
    private CustomerEditValidator _editValidator = new();

    [Parameter] public int? Key { get; set; }

    [Inject] public DialogService DialogService { get; set; }

    [Inject] public ICustomerService CustomerService { get; set; }

    protected override async Task OnParametersSetAsync()
    {
        _editRequestDto = new CustomerEditRequestDto();
        if (Key != null && Key.Value > 0)
        {
            var result = await CustomerService.GetCustomer(Key.Value);
            if (result != null && result.Succeeded && result.Data != null)
            {
                _editRequestDto.Code = result.Data.Code;
                _editRequestDto.Name = result.Data.Name;
                _editRequestDto.Description = result.Data.Description;
            }
        }
    }

    async Task OnSubmit()
    {
        if (Key != null && Key.Value > 0)
        {
            var result = await CustomerService.UpdateCustomer(Key.Value, _editRequestDto);

            if (result.Succeeded)
            {
                DialogService.Close(null);
            }
        }
        else
        {
            var result = await CustomerService.CreateCustomer(_editRequestDto);

            if (result.Succeeded)
            {
                DialogService.Close(null);
            }
        }
    }


    protected void CancelButtonClick(MouseEventArgs args)
    {
        DialogService.Close(null);
    }
}